package pe.gob.sunat.controller;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.WebRequest;

import pe.gob.sunat.domain.Vehiculo;
import pe.gob.sunat.editors.VehiculoEditor;
import pe.gob.sunat.service.VehiculoService;

@Controller
@RequestMapping("/vehiculo/**")
public class VehiculoController {

	@Autowired
	private VehiculoService vehiculoService;

	private Validator validator = Validation.buildDefaultValidatorFactory()
			.getValidator();

	@RequestMapping(value = "vehiculo/insert", method = RequestMethod.POST)
	public String createCash(@ModelAttribute("vehiculo") Vehiculo vehiculo,
			BindingResult result) {
		Assert.notNull(vehiculo, "vehiculo must be provided.");
		for (ConstraintViolation<Vehiculo> constraint : validator
				.validate(vehiculo)) {
			result.rejectValue("" + constraint.getPropertyPath(), null,
					constraint.getMessage());
		}
		if (result.hasErrors())
			return "vehiculo/create";
		vehiculoService.persist(vehiculo);
		return "redirect:/product/" + vehiculo.getPlaca();
	}

	@InitBinder
	public void initBinder(WebDataBinder binder, WebRequest request) {
		binder.registerCustomEditor(Vehiculo.class, new VehiculoEditor(
				vehiculoService));
		// binder.registerCustomEditor(Person.class, new
		// PersonEditor(personService));
	}

}
